package com.teichmann.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

public class ProxyConnectionUtils {

   static SchemeRegistry schemeRegistry = new SchemeRegistry();
   static Logger logger = Logger.getLogger(ConnectionUtils.class.getSimpleName());


   public static HttpClient getClient() {
      HttpParams httpParams = new BasicHttpParams();
      HttpClient client = null;
      if (client == null) {

         schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
         ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

 		 logger.debug("client is null. Instantiating... ");
         client = new DefaultHttpClient(cm, httpParams);
 
         
         ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(new AuthScope("proxy", 3128), new UsernamePasswordCredentials("teichmann", "gremio1903"));
         HttpHost proxy = new HttpHost("proxy", 3128);

         client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

      }

      return client;

   }

   /**
    * @param url
    * @return String Html content
    * @throws Exception
    */
   public static String get(String url) throws IOException {

      HttpClient client = getClient();
      HttpGet method = new HttpGet(URIUtils.encodePath(new StringBuffer(), url).toString());

      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String response = client.execute(method, responseHandler);

      return response;

   }

   public static String post(String value, Map parameters) throws IOException {
      HttpParams httpParams = new BasicHttpParams();
      List<NameValuePair> param = new ArrayList<NameValuePair>();

      Iterator it = parameters.entrySet().iterator();
      while (it.hasNext()) {
         Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
         httpParams.setParameter(pairs.getKey(), pairs.getValue());
         param.add(new BasicNameValuePair(pairs.getKey(), pairs.getValue()));
      }
      HttpClient client = getClient();

      HttpPost method = new HttpPost(value);
      UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(param, HTTP.UTF_8);
      method.setEntity(sendentity);

      // Execute the method.
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String response = client.execute(method, responseHandler);

      method.getEntity().consumeContent();

      return response;
   }

}
